import 'package:get/get.dart';
import 'package:sinosheets/network/api.dart';
import 'package:sinosheets/utils/favorite/product_util.dart';

class ProductDetailLogic extends GetxController {
  Map<String, dynamic> productInfo = {};
  bool isFlashSale = false;
  bool isFavorite = false;
  @override
  void onReady() async {
    // TODO: implement onReady
    super.onReady();
    //接收shopping页面传入的参数
    final Map<String, dynamic> params = Get.arguments;
    bool fromFreeGifts = params['fromFreeGifts'] ?? false;
    if (fromFreeGifts) {
      isFlashSale = true;
      dealFreeGifts(params['productInfo'] ?? {});
    } else {
      productInfo = params['productInfo'] ?? {};
      getProductDetail();
    }
    isFavorite = await getFavorite();
    update();
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
  }

  void dealFreeGifts(Map pInfo) {
    //获取商品详情
    productInfo['id'] = pInfo['id'];
    productInfo['img'] = pInfo['img'];
    productInfo['itemName'] = pInfo['productName'];
    productInfo['productName'] = pInfo['productName'];
    productInfo['inId'] = pInfo['inId'];
    productInfo['price'] = pInfo['price'];
    productInfo['crossedPrice'] = pInfo['crossedPrice'];
    productInfo['productType'] = pInfo['productType'];
    productInfo['shopUrl'] = pInfo['shopUrl'];
    productInfo['symbol'] = pInfo['symbol'];
    update();
  }

  Future<bool> getFavorite() async {
    if (isFlashSale) {
      return await ProductUtil.isFlashSaleProductFavorite(productInfo['id'].toString());
    } else {
      return await ProductUtil.isNormalProductFavorite(productInfo['id'].toString());
    }
  }

  Future<void> collectProduct() async {
    if (isFlashSale) {
      await ProductUtil.toggleFlashSaleProductFavorite(productInfo);
    } else {
      await ProductUtil.toggleNormalProductFavorite(productInfo);
    }
    isFavorite = await getFavorite();
    update();
  }

  //获取商详
  String detailHtml = '';
  Future<void> getProductDetail() async {
    String url = productInfo['detailUrl'] ?? '';
    if (url.isEmpty) {
      return;
    }
    BaseResponse response = await ProductApi.itemDetail(url: url);
    if (response.isSuccess) {
      detailHtml = response.data['desc'] ?? '';
    }
    update();
  }
}
